from common import *
from entity.Config import Config
from entity.Project import Project

import tkinter as tk
from tkinter import filedialog, messagebox

import pathlib


class CreateProjectTool(Window):
    def __init__(self, ddt):
        super().__init__()
        self.root = ddt
        self.window = ddt.create_project_tool
        self.title = "新建项目"
        self.WIDTH = 0
        self.HEIGHT = 0

        """变量"""
        self.project = tk.StringVar()

        """加载组件"""
        self.set_window()

    def set_project(self):
        """新建项目功能"""
        project_label = tk.Label(self.window, text="项目路径")
        project_entry = tk.Entry(self.window, textvariable=self.project, width=30)
        project_button = tk.Button(self.window, text="浏览", command=self.set_dir)
        create_button = tk.Button(self.window, text="确定", command=self.create_project)
        project_label.grid(row=0, column=0)
        project_entry.grid(row=0, column=1)
        project_button.grid(row=0, column=2)
        create_button.grid(row=0, column=3)

    def create_project(self):
        project_config = self.project.get() + "/" + "app.dsft.ini"
        self.project = pathlib.Path(self.project.get())
        # 设置项目属性
        self.root.project = Project(self.project, pathlib.Path(project_config))
        # 创建项目
        self.mkdir_project()

    def set_dir(self):
        project = filedialog.askdirectory()
        if project == "" or project is None:
            return 0
        self.project.set(project)

    def mkdir_project(self):
        # 如果目录为空直接创建项目，如果目录不为空提示是否覆盖
        if self.root.project.project.is_dir() and not dir_empty(self.root.project.project):
            if not messagebox.askyesno("提示", "已有文件夹，是否覆盖原文件夹？"):
                return 0
            rm_tree(self.root.project.project)

        if not self.root.project.project.is_dir():
            self.root.project.project.mkdir()
        self.root.project.config.save()
        self.root.window.title(f"开发者工具  -{self.root.project.name}")
        # 创建后完毕工具
        self.window.destroy()
        # 加载信息框
        self.root.load_project_information()
        self.root.init()

    def set_function(self):
        """重写方法"""
        # 窗口置顶弹出
        self.window.wm_attributes('-topmost', 1)
        # 禁止拉伸
        self.window.resizable(0, 0)
        # 去掉窗口最大化最小化按钮，只保留关闭
        self.window.attributes("-toolwindow", 2)
        # 新建项目信息
        self.set_project()